package com.yyw.foodie.config;

import com.yyw.foodie.common.Result;
import com.yyw.foodie.exceptions.NotLoginException;
import com.yyw.foodie.exceptions.NullParamException;
import com.yyw.foodie.exceptions.OrderStatusException;
import com.yyw.foodie.exceptions.PayException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * @author 易煜玮
 * @ClassName ExceptionController.java
 * @Description 全局异常捕捉器
 * @createTime 2021年05月29日 17:22:00
 */
@ControllerAdvice
public class ExceptionController {

    /**
     * 用户未登录请求时候抛出异常
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = NotLoginException.class)
    public Result notLogin(NotLoginException exception) {
        exception.printStackTrace();
        return Result.errorMsg(exception.getMessage());
    }


    /**
     * 参数为空的时候抛出异常
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = NullParamException.class)
    public Result nullParam(NullParamException exception) {
        exception.printStackTrace();
        return Result.errorMsg(exception.getMessage());
    }

    /**
     * 支付相关的异常
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = PayException.class)
    public Result payException(PayException exception) {
        exception.printStackTrace();
        return Result.errorMsg(exception.getMessage());
    }

    /**
     * 文件上传超过大小异常
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
    public Result maxUploadEx(MaxUploadSizeExceededException exception) {
        exception.printStackTrace();
        return Result.errorMsg("文件大小超出限制，请控制大小在520kb");
    }

    /**
     * 订单状态相关异常
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = OrderStatusException.class)
    public Result orderEx(OrderStatusException exception) {
        exception.printStackTrace();
        return Result.errorMsg(exception.getMessage());
    }

    /**
     * 运行时异常
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    public Result runTime(RuntimeException exception) {
        exception.printStackTrace();
        return Result.errorMsg(exception.getMessage());
    }


    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result runTime(Exception exception) {
        exception.printStackTrace();
        return Result.errorMsg("出现异常,异常信息为: " + exception.getMessage());
    }
}
